//
//  BDMyOrderDetailViewController.m
//  iOS_beboy
//
//  Created by wen on 2017/9/21.
//  Copyright © 2017年 com.8xiong. All rights reserved.
//

#import "BDMyOrderDetailViewController.h"
#import "BDMyOrderLayout.h"
#import "BDGeneralCell.h"
#import "BDShopInfoDeatilViewController.h"
#import "BDMyOrderCouponModel.h"
#import "BDRefundViewController.h"
#import "BDUserModel.h"

@interface BDMyOrderDetailViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *customCouponInfoView;
@property (nonatomic, strong) NSMutableArray *datasource;
@property (nonatomic, strong) BDMyOrderCouponModel *couponModel;

@end

@implementation BDMyOrderDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = ASLocalizedString(@"订单详情");
    _datasource = [NSMutableArray array];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self requesDatasource];
}

- (void)requesDatasource{
    if ([_model isKindOfClass:[BDMyOrderLayout class]]) {
        BDMyOrderLayout *layout = _model;
        NSInteger code = [layout.order.object[@"code"] integerValue];
        NSString *url = [NSString stringWithFormat:@"%@shopCouponPurchases/%@", KBDBaseURL, @(code)];
        NSString *headValid = [BDUserModel getHeaderValidation];

        RACSignal *signal = [[BDNetworkingServer v2_GET:url parameters:nil validation:headValid automaticProcessingError:YES] execute:nil];
        [signal subscribeNext:^(id  _Nullable x) {
            _couponModel = [BDMyOrderCouponModel mj_objectWithKeyValues:x];
            [self dealDatasource];
            [self.tableView reloadData];
        }];
        [signal subscribeError:^(NSError * _Nullable error) {
            [MBManager showBriefAlert:ASLocalizedString(@"请求失败")clickHidden:YES clickBlock:nil];
        }];
    }
}

- (void)dealDatasource{
    _customCouponInfoView = nil;
    [_datasource removeAllObjects];
    
    if ([_model isKindOfClass:[BDMyOrderLayout class]]) {
        BDMyOrderLayout *layout = _model;
        NSDecimalNumber *red_amount = [[NSDecimalNumber decimalNumberWithString:layout.order.total_amount] decimalNumberBySubtracting:[NSDecimalNumber decimalNumberWithString:layout.order.receipt_amount]];
        
        NSString *shopName = nil;
        NSDictionary *shopInfo = layout.order.object[@"shop"];
        if ([shopInfo isKindOfClass:[NSDictionary class]]) {
            shopName = shopInfo[@"title"];
        }
        if ([shopName isNotBlank] == NO) {
            shopName = ASLocalizedString(@"该店不存在");
        }
        
        NSMutableArray *firstArray = @[].mutableCopy;
        [firstArray addObject:[BDGeneralModel new].titleEqual(shopName).imageEqual(@"dianpu").accessoryTypeTypeEqual(BDGeneralCellAccessoryTypeDisclosureIndicator)];
        [_datasource addObject:firstArray];
        
        NSMutableArray *secondArray = @[].mutableCopy;
        [secondArray addObject:[BDGeneralModel new].titleEqual(ASLocalizedString(@"原价：")).subTitleEqual([NSString stringWithFormat:@"¥%@", layout.order.total_amount])];
        [secondArray addObject:[BDGeneralModel new].titleEqual(ASLocalizedString(@"红包：")).subTitleEqual([NSString stringWithFormat:@"-¥%@", red_amount])];
        [secondArray addObject:[BDGeneralModel new].titleEqual(ASLocalizedString(@"合计：")).subTitleEqual([NSString stringWithFormat:@"¥%@", layout.order.receipt_amount])];
        [_datasource addObject:secondArray];
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.datasource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [self.datasource[section] count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 45;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (section == 0) {
        return self.customCouponInfoView.height;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 15;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section == 0) {
        return self.customCouponInfoView;
    }
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BDGeneralModel *generalModel = self.datasource[indexPath.section][indexPath.row];
    __weak BDGeneralModel *weakModel = generalModel;
    BDGeneralCell *cell = [BDGeneralCell cellForTableView:tableView model:generalModel indexPath:indexPath identifier:@"orderDetail"];
    cell.subviewBlock = ^(BDGeneralCell *generalCell) {
        
        generalCell.imageView.size = CGSizeMake(20, 20);
        generalCell.imageView.left = 10;
        generalCell.imageView.centerY = generalCell.height / 2.0;
        
        generalCell.textLabel.font = [UIFont systemFontOfSize:15];
        generalCell.textLabel.textColor = [UIColor colorWithHexString:@"#1c1c1c"];
        [generalCell.textLabel sizeToFit];
        generalCell.textLabel.centerY = generalCell.height / 2.0;
        if ([weakModel.image isNotBlank]) {
            generalCell.textLabel.left = generalCell.imageView.right + 10;
        }else{
            generalCell.textLabel.left = 10;
        }
        
        generalCell.detailTextLabel.font = [UIFont systemFontOfSize:15];
        generalCell.detailTextLabel.textColor = [UIColor colorWithHexString:@"#1c1c1c"];
        [generalCell.detailTextLabel sizeToFit];
        generalCell.detailTextLabel.centerY = generalCell.height / 2.0;
        generalCell.detailTextLabel.right = generalCell.width - 10;

    };
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        //这里跳转到商家
        if ([_model isKindOfClass:[BDMyOrderLayout class]]) {
            BDMyOrderLayout *layout = _model;
            NSString *shopId = [NSString stringWithFormat:@"%@", layout.order.object[@"shop_id"]];
            NSString *shopName = layout.order.object[@"shop"][@"title"];
            if ([shopId isNotBlank] && [shopName isNotBlank]) {
                BDShopInfoDeatilViewController *infoVc = [[BDShopInfoDeatilViewController alloc] init];
                infoVc.shopID = shopId;
                infoVc.title = shopName;
                [self.navigationController pushViewController:infoVc animated:YES];
            }else{
                [[UIApplication sharedApplication].keyWindow alertWithTitle:ASLocalizedString(@"提示")message:ASLocalizedString(@"该店不存在，无法查看")type:AlertTypeAlert cancleTitle:ASLocalizedString(@"确定")otherTitle:nil clickBlock:nil];;
            }
        }
    }
}

- (UITableView *)tableView{
    if (!_tableView) {
        self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, kBDTopHeight, kBDScreenWidth, kBDScreenHeight - kBDTopHeight) style:UITableViewStyleGrouped];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.sectionFooterHeight = 0;
        _tableView.sectionHeaderHeight = 0;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.tableFooterView = [[UIView alloc] init];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

- (UIView *)customCouponInfoView{
    if (!_customCouponInfoView) {
        self.customCouponInfoView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 0)];
        _customCouponInfoView.backgroundColor = [UIColor whiteColor];
        
        UILabel *titleLabel = [[UILabel alloc] init];
        titleLabel.font = [UIFont systemFontOfSize:18];
        titleLabel.textColor = [UIColor colorWithHexString:@"#1c1c1c"];
        [_customCouponInfoView addSubview:titleLabel];
        
        UIImageView *imageView = [[UIImageView alloc] init];
        [_customCouponInfoView addSubview:imageView];
        
        UILabel *contnenLabel = [[UILabel alloc] init];
        contnenLabel.font = [UIFont systemFontOfSize:14];
        contnenLabel.textColor = [UIColor colorWithHexString:@"#767676"];
        contnenLabel.numberOfLines = 0;
        [_customCouponInfoView addSubview:contnenLabel];
        
        UIView *dashLine = [[UIView alloc] initWithFrame:CGRectMake(15, 0, kBDScreenWidth - 30, 1)];
        [dashLine drawLineLength:5 lineSpacing:2 lineColor:[UIColor colorWithHexString:@"#e0e0e0"] verticality:NO];
        [_customCouponInfoView addSubview:dashLine];
        
        UILabel *curentPriceLabel = [[UILabel alloc] init];
        curentPriceLabel.font = [UIFont systemFontOfSize:13];
        curentPriceLabel.textColor = [UIColor colorWithHexString:@"#767676"];
        [_customCouponInfoView addSubview:curentPriceLabel];
        
        UILabel *oldPriceLabel = [[UILabel alloc] init];
        oldPriceLabel.font = [UIFont systemFontOfSize:15];
        oldPriceLabel.textColor = [UIColor colorWithHexString:@"#767676"];
        [_customCouponInfoView addSubview:oldPriceLabel];
        
        UILabel *peopleNumberLabel = [[UILabel alloc] init];
        peopleNumberLabel.font = [UIFont systemFontOfSize:15];
        peopleNumberLabel.textColor = [UIColor colorWithHexString:@"#767676"];
        [_customCouponInfoView addSubview:peopleNumberLabel];
        
        UIButton *qianggouButton = [UIButton buttonWithType:UIButtonTypeCustom];
        qianggouButton.titleLabel.font = [UIFont systemFontOfSize:13];
        [_customCouponInfoView addSubview:qianggouButton];
        
        UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kBDScreenWidth, 0.5)];
        line.backgroundColor = [UIColor colorWithHexString:@"#e0e0e0"];
        [_customCouponInfoView addSubview:line];
        
        UILabel *timeLabel = [[UILabel alloc] init];
        timeLabel.font = [UIFont systemFontOfSize:15];
        timeLabel.textColor = [UIColor colorWithHexString:@"#767676"];
        [_customCouponInfoView addSubview:timeLabel];
        
        if ([_model isKindOfClass:[BDMyOrderLayout class]]) {
            
            titleLabel.text = _couponModel.title;
            [titleLabel sizeToFit];
            titleLabel.top = 10;
            titleLabel.centerX = _customCouponInfoView.width / 2.0;
            
            [imageView sd_setImageWithURL:[NSURL URLWithString:_couponModel.cover] placeholderImage:[UIImage imageNamed:@"shop_pic"]];
            imageView.size = CGSizeMake(101, 76);
            imageView.top = titleLabel.bottom + 24;
            imageView.left = 15;
            
            contnenLabel.text = _couponModel.content;
            contnenLabel.width = kBDScreenWidth - imageView.right - 15 - 15;
            contnenLabel.height = [contnenLabel.text heightWithFont:contnenLabel.font width:contnenLabel.width];
            contnenLabel.left = imageView.right + 15;
            contnenLabel.top = imageView.top;
            
            dashLine.top = MAX(contnenLabel.bottom, imageView.bottom) + 20;
            
            NSString *string = [NSString stringWithFormat:ASLocalizedString(@"折扣价：¥%@"), [NSDecimalNumber decimalNumberWithString:_couponModel.amount]];
            NSMutableAttributedString *attribuString = [[NSMutableAttributedString alloc] initWithString:string];
            NSRange range = [string rangeOfString:[NSString stringWithFormat:@"¥%@", [NSDecimalNumber decimalNumberWithString:_couponModel.amount]]];
            [attribuString setAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16],NSForegroundColorAttributeName:[UIColor colorWithHexString:@"ff4f00"]} range:range];
            curentPriceLabel.attributedText = attribuString;
            [curentPriceLabel sizeToFit];
            curentPriceLabel.left = 15;
            curentPriceLabel.top = dashLine.bottom + 15;
            
            oldPriceLabel.text = [NSString stringWithFormat:ASLocalizedString(@"原价：¥%@"), [NSDecimalNumber decimalNumberWithString:_couponModel.price]];
            [oldPriceLabel sizeToFit];
            oldPriceLabel.bottom = curentPriceLabel.bottom;
            oldPriceLabel.left = curentPriceLabel.right + 15;
            
            peopleNumberLabel.text = [NSString stringWithFormat:ASLocalizedString(@"推荐人数：%@人"), @(_couponModel.rec_num)];
            [peopleNumberLabel sizeToFit];
            peopleNumberLabel.top = curentPriceLabel.bottom + 15;
            peopleNumberLabel.left = 15;
            
            qianggouButton.size = CGSizeMake(65, 30);
            qianggouButton.centerY = peopleNumberLabel.top - 7.5;
            qianggouButton.right = kBDScreenWidth - 15;
            qianggouButton.layer.masksToBounds = YES;
            qianggouButton.layer.cornerRadius = 3;
            switch (_couponModel.status) {
                case BDMyOrderCouponStatusNotUse:
                    [qianggouButton setTitle:ASLocalizedString(@"申请退款")forState:UIControlStateNormal];
                    [qianggouButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                    qianggouButton.backgroundColor = [UIColor colorWithHexString:@"#ff992b"];
                    break;
                case BDMyOrderCouponStatusUsed:
                    [qianggouButton setTitle:ASLocalizedString(@"再来一单")forState:UIControlStateNormal];
                    [qianggouButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                    qianggouButton.backgroundColor = [UIColor colorWithHexString:@"#ff992b"];
                    break;
                case BDMyOrderCouponStatusOverdue:
                    [qianggouButton setTitle:ASLocalizedString(@"已失效")forState:UIControlStateNormal];
                    [qianggouButton setTitleColor:[UIColor colorWithHexString:@"#767676"] forState:UIControlStateNormal];
                    qianggouButton.backgroundColor = [UIColor whiteColor];
                    break;
                case BDMyOrderCouponStatusRefunding:
                    [qianggouButton setTitle:ASLocalizedString(@"退款中")forState:UIControlStateNormal];
                    [qianggouButton setTitleColor:[UIColor colorWithHexString:@"#767676"] forState:UIControlStateNormal];
                    qianggouButton.backgroundColor = [UIColor whiteColor];
                    break;
                case BDMyOrderCouponStatusRefunded:
                    [qianggouButton setTitle:ASLocalizedString(@"已退款")forState:UIControlStateNormal];
                    [qianggouButton setTitleColor:[UIColor colorWithHexString:@"#767676"] forState:UIControlStateNormal];
                    qianggouButton.backgroundColor = [UIColor whiteColor];
                    break;
                case BDMyOrderCouponStatusCommented:
                    [qianggouButton setTitle:ASLocalizedString(@"再来一单")forState:UIControlStateNormal];
                    [qianggouButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
                    qianggouButton.backgroundColor = [UIColor colorWithHexString:@"#ff992b"];
                    break;
                default:
                    break;
            }
            
            [qianggouButton setEnlargeEdgeWithTop:10 right:10 bottom:10 left:10];
            [[qianggouButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
                if (_couponModel.status == BDMyOrderCouponStatusNotUse) {
                    //申请退款
//                    BDRefundViewController *refundVC = [[BDRefundViewController alloc] init];
//                    refundVC.reservation = reservation;
//                    [self.navigationController pushViewController:refundVC animated:YES];
                }else if (_couponModel.status == BDMyOrderCouponStatusUsed || _couponModel.status == BDMyOrderCouponStatusCommented){
                    //在来一单
                }
            }];
            
            line.top = peopleNumberLabel.bottom + 15;
            
            
            NSDate *start_at = [NSDate dateWithTimeIntervalSince1970:_couponModel.start_at];
            NSDate *end_at = [NSDate dateWithTimeIntervalSince1970:_couponModel.end_at];
            
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"YYYY-mm-dd"];
            
            NSString *startString = [formatter stringFromDate:start_at];
            NSString *endString = [formatter stringFromDate:end_at];
            timeLabel.text = [NSString stringWithFormat:ASLocalizedString(@"有效期：%@ 至 %@"), startString, endString];
            [timeLabel sizeToFit];
            timeLabel.centerY = line.bottom + 20;
            timeLabel.left = 15;
            
            _customCouponInfoView.height = line.bottom + 40;
        }
    }
    return _customCouponInfoView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
